"use client";

import ClientLoading from "@/components/ClientLoading";
import { Form, Input } from "@/components/Form";
import { POST, PUT } from "@/utils/fetch";
import { useRouter } from "next/navigation";
import React, { useState } from "react";

const emptyCfip: Cfip = {
  name: "",
  code: "",
  ip: "",
};

export default function CfipInputUI({
  data = { ...emptyCfip },
}: {
  data?: Cfip;
}) {
  const [cfip, setCfip] = useState(data);
  const [isLoading, setLoading] = useState(false);
  const router = useRouter();

  const changeValue =
    (key: string) => (e: React.ChangeEvent<HTMLInputElement>) => {
      const v = e.target.value.trim();
      setCfip({ ...cfip, [key]: v });
    };

  const submitHandler = async () => {
    setLoading(true);
    try {
      const resp: JsonResp<any> = cfip.id
        ? await PUT("/cfip", { ...cfip })
        : await POST("/cfip", { ...cfip });
      if (resp.code !== 0) {
        throw new Error(resp.msg);
      }
      router.push(`/cfip?msg=操作成功&_r=${Math.random()}`);
    } catch (e) {
      alert((e as Error).message);
      console.log(e);
    } finally {
      setLoading(false);
    }
  };

  return (
    <>
      {isLoading && <ClientLoading />}
      {/* <div>{JSON.stringify(cfip)}</div> */}
      <Form onSubmit={submitHandler}>
        <Input
          label="名称"
          onChange={changeValue("name")}
          value={cfip.name}
          required
        />
        <Input
          label="代码"
          onChange={changeValue("code")}
          value={cfip.code}
          required
        />
        <Input
          label="IP"
          onChange={changeValue("ip")}
          value={cfip.ip}
          required
        />
      </Form>
    </>
  );
}
